package com.css.fxfzypg.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * limanman
 * redis分布式锁
 * 2022.4.25
 */
@Component
@Slf4j
@Data
public class RedisLockUtil {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 加锁;无阻塞
     * @param key
     * @param expireTime
     * @param value 可以是32位uuid，主要是为每个线程设置一个标志位，用于判断释放锁为本线程的锁
     * @return
     */
    public Boolean lock(String key, String value, long expireTime){
        long start = System.currentTimeMillis();
        //循环去抢锁，超时则返回
        for (;;){
            //set命令返回ok，则代表抢锁成功
            Boolean rel = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
            if (rel){
                return true;
            }
            //否则循环等待，在10分钟内未获取到锁，则返回
            long end = System.currentTimeMillis() - start;
            if (end >= 600000){
                return false;
            }

        }
    }



    /**
     *  释放锁
     **/
    public Long releaseLock(String key, String value){
        //lau脚本。保证释放锁为原子操作
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class);
        //释放锁成功为1. 其他情况返回0
        Long releaseStatus = (Long)this.redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        return releaseStatus;
    }

}
